/*
Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]
*/

/* Complexity: O(n^2) */
class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector<vector<string> >res;
        if (!s.length()) return res;
        vector<string> resone;
        addPalindrome(0, s, resone, res);
        return res;
    }
private:
    void addPalindrome(int start, string &s, vector<string> &resone, vector<vector<string> >&res) {
        if (start == s.length()) {res.push_back(resone); return;}
        // test each subcase
        for (int i = start; i < s.length(); i++) {
            if (IsPalindrome(start, i, s)) {
                resone.push_back(s.substr(start,i-start+1));
                addPalindrome(i + 1, s, resone, res);
                resone.pop_back();
            }
        }
    }
    bool IsPalindrome(int start, int end, string &s) {
        while (start < end) {
            if (s[start] != s[end]) return false;
            start ++; end--;
        }
        return true;
    }
};
